#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "poc.settings")# project_name 项目名称
django.setup()
from django.http import JsonResponse,HttpResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.settings import api_settings
from restapi.models import PocUserRank
from restapi.models import PocUser
from restapi.serializers import UserSerializer
from restapi.utils.retcode import *
from django.contrib.auth.hashers import make_password, check_password
import datetime

log = logger.get_logger(__name__)

@api_view(['GET'])
def get_user_list(request):
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
    paginator = pagination_class()
    user_list = PocUser.objects.all()
    page = paginator.paginate_queryset(user_list, request)
    ret_ser = UserSerializer(page, many=True)
    return paginator.get_paginated_response(ret_ser.data)

@api_view(['POST'])
def user_login(request):
    data = JSONParser().parse(request)
    try:
        username = data['user_name']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入用户名"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    try:
        userpass = data['user_pass']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入用户密码"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    try:
        inserttime=data['insert_time']
    except Exception:
        return JsonResponse(retcode({},"9999","登录时间有误"),safe=True,status=status.HTTP_400_BAD_REQUEST)
    try:
        user_authentic= PocUser.objects.get(user_name=username)
    except PocUser.DoesNotExist:
        return JsonResponse(retcode({}, "2", "用户名不存在"), safe=True)
    # if user_authentic.user_pass!=userpass:
    if check_password(userpass, user_authentic.user_pass) is not True:
        return JsonResponse(retcode({}, "0", "用户名或密码错误"), safe=True,
                            status=status.HTTP_200_OK);
    _insert_time = datetime.datetime.fromtimestamp(inserttime)
    user_authentic.insert_time = _insert_time
    try:
        user_authentic.save()
    except Exception:
        return JsonResponse(retcode({}, "9999", "时间更新失败"), safe=True, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return JsonResponse(retcode(UserSerializer(user_authentic).data, "1", "Success"), safe=True,
                        status=status.HTTP_200_OK)

@api_view(['POST'])
def create_user(request):
    data = JSONParser().parse(request)
    try:
        user_name = data['user_name']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入用户名"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    try:
        user_pass = data['user_pass']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入用户密码"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    try:
        user_rank = data['user_rank']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入权限等级"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    try:
        user_rank_model=PocUserRank.objects.get(rank_id=user_rank);
    except PocUserRank.DoesNotExist:
        return JsonResponse(retcode({}, "9999", "请输入权限等级"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    # try:
    #     insert_time = data['insert_time']
    # except Exception:
    #     return JsonResponse(retcode({}, "9999", "请输入注册时间"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    # _insert_time = datetime.datetime.fromtimestamp(insert_time)
    user_model = PocUser(user_name=user_name, user_pass=make_password(user_pass),user_rank=user_rank_model)
    try:
        user_model.save()
    except Exception as e:
        # log.error(repr(e))
        return JsonResponse(retcode({}, "4", "用户创建失败"), safe=True, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return JsonResponse(retcode(UserSerializer(user_model).data, "0000", "Success"), safe=True,
                        status=status.HTTP_200_OK)

@api_view(["POST"])
def judgePass(request):
    data=JSONParser().parse(request)
    try:
        user_name=data['user_name']
    except Exception:
        return JsonResponse(retcode({},"9999","用户名有误"),safe=True,status=status.HTTP_400_BAD_REQUEST)
    try:
        user_pass=data['user_pass']
    except Exception:
        JsonResponse(retcode({},"9999","密码输入有误"),safe=True,status=status.HTTP_400_BAD_REQUEST)
    try:
        user_authentic= PocUser.objects.get(user_name=user_name)
    except PocUser.DoesNotExist:
        return JsonResponse(retcode({}, "2", "用户名不存在"), safe=True)
    if check_password(user_pass, user_authentic.user_pass) is not True:
        return JsonResponse(retcode({}, "0", "密码错误"), safe=True,
                            status=status.HTTP_200_OK);
    return JsonResponse(retcode(UserSerializer(user_authentic).data, "1", "Success"), safe=True,
                        status=status.HTTP_200_OK)

@api_view(["POST"])
def user_pass_update(request):
    data=JSONParser().parse(request)
    try:
        user_name=data['user_name']
    except Exception:
        return JsonResponse(retcode({},"9999","用户名有误"),safe=True,status=status.HTTP_404_NOT_FOUND)
    try:
        user_pass=data['user_pass']
    except Exception:
        return JsonResponse(retcode({},"9999","密码输入有误"),safe=True,status=status.HTTP_404_NOT_FOUND)
    try:
        user_model_pass = PocUser.objects.get(user_name=user_name)
    except PocUser.DoesNotExist:
        return JsonResponse(retcode({}, "9999", "用户信息不存在"), safe=True, status=status.HTTP_404_NOT_FOUND)
    # try:
    #     user_id=data['user_id']
    # except Exception:
    #     return JsonResponse(retcode({},"9999","用户名不存在"),safe=True,status=status.HTTP_404_NOT_FOUND)
    try:
        user_model_pass = PocUser.objects.get(user_name=user_name)
    except PocUser.DoesNotExist:
        return JsonResponse(retcode({}, "9999", "用户信息不存在"), safe=True, status=status.HTTP_404_NOT_FOUND)
    user_model_pass.user_pass=make_password(user_pass)
    try:
        user_model_pass.save()
    except Exception:
        return JsonResponse(retcode({}, "9999", "密码重置失败"), safe=True, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return JsonResponse(retcode(UserSerializer(user_model_pass).data, "0000", "Success"), safe=True,
                        status=status.HTTP_200_OK)

@api_view(["POST"])
def user_update(request):
    data=JSONParser().parse(request)
    log.info(data)
    try:
        user_id = data['user_id']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入poc的id"), safe=True, status=status.HTTP_404_NOT_FOUND)
    try:
        user_name = data['user_name']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入用户名"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    # try:
    #     user_pass = data['user_pass']
    # except Exception:
    #     return JsonResponse(retcode({}, "9999", "请输入用户密码"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    try:
        user_rank = data['user_rank']
    except Exception:
        return JsonResponse(retcode({}, "9999", "请输入权限等级"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    try:
        user_rank_model=PocUserRank.objects.get(rank_id=user_rank);
    except PocUserRank.DoesNotExist:
        return JsonResponse(retcode({}, "9999", "请输入权限等级"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    # try:
    #     insert_time = data['insert_time']
    # except Exception:
    #     return JsonResponse(retcode({}, "9999", "请输入注册时间"), safe=True, status=status.HTTP_400_BAD_REQUEST)
    # _insert_time = datetime.datetime.fromtimestamp(insert_time)
    try:
        user_model = PocUser.objects.get(user_id=user_id)
    except PocUser.DoesNotExist:
        return JsonResponse(retcode({}, "9999", "用户信息不存在"), safe=True, status=status.HTTP_404_NOT_FOUND)
    # _insert_time = datetime.datetime.fromtimestamp(insert_time)
    user_model.user_name=user_name
    user_model.user_rank=user_rank_model
    # user_model.user_pass=make_password(user_pass)
    # user_model.insert_time=_insert_time
    try:
        user_model.save()
    except Exception:
        return JsonResponse(retcode({}, "9999", "用户信息更新失败"), safe=True, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return JsonResponse(retcode(UserSerializer(user_model).data, "0000", "Success"), safe=True, status=status.HTTP_200_OK)

@api_view(['DELETE'])
def delete_user(request, user_id):
    try:
        user_model = PocUser.objects.get(user_id=user_id)
        # 删除user
        user_model.delete()
    except Exception:
        return JsonResponse(retcode({}, "9999", "用户删除失败"), safe=True,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return JsonResponse(retcode({}, "0000", "Success"), safe=True, status=status.HTTP_200_OK)
